package com.example.music.service;

import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import com.example.music.R;
import com.example.music.activity.MusicActivity;
import com.example.music.model.AppConstants;
import com.example.music.utils.NotificationReceiver;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class MusicService extends Service {
    public static boolean isPlaying = false;
    private MediaPlayer player;
    private Timer timer;

    // 播放控制Action
    public static final String ACTION_PLAY_PAUSE = "com.example.music.ACTION_PLAY_PAUSE";
    public static final String ACTION_PLAY = "com.example.music.ACTION_PLAY";
    public static final String ACTION_PAUSE = "com.example.music.ACTION_PAUSE";
    public static final String ACTION_CLOSE = "com.example.music.ACTION_CLOSE";
    public static final String ACTION_NEXT = "com.example.music.ACTION_NEXT";
    public static final String ACTION_PREV = "com.example.music.ACTION_PREV";

    // 通知相关参数
    private static final int NOTIFICATION_ID = 1;
    private static final String CHANNEL_ID = "music_channel";
    private String currentTitle = "正在播放";
    private String currentArtist = "未知艺术家";
    private Bitmap image;

    private final IBinder binder = new MusicControl();
    public MusicService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        player = new MediaPlayer();
        createNotificationChannel();
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "音乐播放通道",
                    NotificationManager.IMPORTANCE_LOW
            );
            getSystemService(NotificationManager.class).createNotificationChannel(channel);
        }
    }

    private Notification buildNotification() {
        // 主界面Intent
        Intent mainIntent = new Intent(this, MusicActivity.class);
        mainIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent mainPending = PendingIntent.getActivity(
                this, 0, mainIntent, PendingIntent.FLAG_IMMUTABLE);

        // 创建控制按钮
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle(currentTitle)
                .setContentText(currentArtist)
                .setSmallIcon(R.drawable.ic_icon)
                .setLargeIcon(image)
                .setContentIntent(mainPending)
                .addAction(R.drawable.ic_previous_1, "上一首", createPendingIntent(ACTION_PREV))
                .addAction(getPlayPauseIcon(), "播放/暂停", createPendingIntent(ACTION_PLAY_PAUSE))
                .addAction(R.drawable.ic_next_1, "下一首", createPendingIntent(ACTION_NEXT))
                .setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
                        .setShowActionsInCompactView(0, 1, 2))
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .setOngoing(true);

        return builder.build();
    }

    private PendingIntent createPendingIntent(String action) {
        Intent intent = new Intent(this, NotificationReceiver.class);
        intent.setAction(action);
        return PendingIntent.getBroadcast(this, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
    }

    private int getPlayPauseIcon() {
        return isPlaying ? R.drawable.ic_play_1 : R.drawable.ic_pause_1;
    }

    // 更新通知内容
    private void updateNotification() {
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        NotificationManagerCompat.from(this)
                .notify(NOTIFICATION_ID, buildNotification());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Notification notification = buildNotification();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            startForeground(NOTIFICATION_ID, notification, FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK);
        } else {
            startForeground(NOTIFICATION_ID, notification);
        }

        if (intent != null) {

            String action = intent.getAction();
            if (action != null) {
                switch (action) {
                    case ACTION_PLAY_PAUSE:
                        if(isPlaying)
                        {
                            if (player != null && player.isPlaying()) {
                                player.pause();
                                currentTitle = "已暂停";
                                isPlaying=false;
                                updateNotification();
                                sendPlayStateToActivity(false);
                            }
                        }else{
                            if (player != null && !player.isPlaying()) {
                                player.start();
                                currentTitle = "正在播放";
                                isPlaying=true;
                                updateNotification();
                                sendPlayStateToActivity(true);
                            }
                        }
                        break;
                    case ACTION_PLAY:
                        player.start();
                        currentTitle = "正在播放";
                        isPlaying=true;
                        updateNotification();
                        break;
                    case ACTION_PAUSE:
                        player.pause();
                        currentTitle = "已暂停";
                        isPlaying=false;
                        updateNotification();
                        break;
                    case ACTION_NEXT:
                        sendNextToActivity();
                        break;
                    case ACTION_PREV:
                        sendPreToActivity();
                        break;
                }
            }
        }
        return START_STICKY;
    }

    private void sendPlayStateToActivity(boolean isPlaying) {
        Intent intent = new Intent(AppConstants.ACTION_UPDATE_PLAY_BUTTON);
        intent.putExtra(AppConstants.EXTRA_IS_PLAYING, isPlaying);
        intent.setPackage(getPackageName());
        Log.d("SendBroadcast", "发送广播，isPlaying=" + isPlaying);
        sendBroadcast(intent);
        // 持久化状态到SharedPreferences
        SharedPreferences prefs = getApplicationContext().getSharedPreferences("PlayerPrefs", Context.MODE_PRIVATE);
        prefs.edit().putBoolean(AppConstants.EXTRA_IS_PLAYING, isPlaying).apply();
    }

    private void sendNextToActivity()
    {
        Intent intent=new Intent(AppConstants.NEXT);
        Log.d("SendBroadcast", "发送广播，NEXT" );
        sendBroadcast(intent);
    }
    private void sendPreToActivity()
    {
        Intent intent=new Intent(AppConstants.PRE);
        Log.d("SendBroadcast", "发送广播，PRE" );
        sendBroadcast(intent);
    }

    // 获取专辑封面
    private Bitmap getAlbumArt(String filePath) throws IOException {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            byte[] artBytes = retriever.getEmbeddedPicture();
            if (artBytes != null) {
                return BitmapFactory.decodeByteArray(artBytes, 0, artBytes.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            retriever.release();
        }
        return null;
    }

    public class MusicControl extends Binder {
        public void fir(String name)
        {
            currentArtist=name;
        }
        public int play(String i) throws IOException {
            image=getAlbumArt(i);
            Uri uri = Uri.parse(i);
            try {
                player.reset();
                player = MediaPlayer.create(getApplicationContext(), uri);
                player.start();
                currentTitle = "音乐" + i;
                updateNotification();
                addTimer();
            } catch (Exception e) {
                e.printStackTrace();
            }
            isPlaying=true;
            return player.getDuration();
        }

        public void pausePlay() {
            if (player != null && player.isPlaying()) {
                player.pause();
                currentTitle = "已暂停";
                updateNotification();
                isPlaying=false;
            }
        }

        public void continuePlay() {
            if (player != null && !player.isPlaying()) {
                player.start();
                currentTitle = "正在播放";
                updateNotification();
                isPlaying=true;
            }
        }

        public void seekTo(int progress) {
            if (player != null) {
                player.seekTo(progress);
            }
        }
    }

    // 添加计时器（保持原有逻辑）
    public void addTimer() {
        if (timer == null) {
            timer = new Timer();
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    if (player == null) return;
                    int duration = player.getDuration();
                    int currentPosition = player.getCurrentPosition();
                    Message msg = MusicActivity.handler.obtainMessage();
                    Bundle bundle = new Bundle();
                    bundle.putInt("duration", duration);
                    bundle.putInt("currentPosition", currentPosition);
                    msg.setData(bundle);
                    MusicActivity.handler.sendMessage(msg);
                }
            };
            timer.schedule(task, 5, 500);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (player != null) {
            player.release();
            player = null;
        }
        stopForeground(true);
        NotificationManagerCompat.from(this).cancel(NOTIFICATION_ID);
    }
}